package com.lgmshare.component.storage;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * SharedPreference放在data/data/包名/下面。
 * 是占用内存得，如果保存大量的数据，需要放到sdcard下去，所以SharedPreferences不方便，直接用Properties类的方式比较好。
 * 可以把文件当作字符串传入，能访问获取正确值就好！
 *
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2017/12/7 15:35
 */
class PropertiesHelper extends Properties {

    /**
     * 配置文件路径(例如：/data/data/com.xxx.xxx/config.properties)
     */
    private String mPropertyPath;

    private PropertiesHelper(String path) {
        mPropertyPath = path;
    }

    public static PropertiesHelper getInstance(Context context, String name) {
        File file = new File(context.getCacheDir().getPath() + "/" + name);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        PropertiesHelper pro = new PropertiesHelper(file.getPath());
        try {
            InputStream is = new FileInputStream(file);
            pro.load(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pro;
    }

    @Override
    public Object setProperty(String key, String value) {
        super.setProperty(key, value);
        try {
            this.store(new FileOutputStream(this.mPropertyPath),
                    "utf-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    @Override
    public String getProperty(String key) {
        return super.getProperty(key);
    }

    public Object removeProperty(String key) {
        Object value = remove(key);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(this.mPropertyPath);
            this.store(fos, null);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
        return value;
    }
}
